//
//  YpViewController.m
//  KIASupervisory
//
//  Created by apple on 15/7/19.
//  Copyright (c) 2015年 MyCompany. All rights reserved.
//

#import "TongzhiViewController.h"
#import "TongzhiListViewController.h"
#import "MainViewController.h"
#import "SXDetailModel.h"
#import "SXDetailImgModel.h"
#import "SXHTTPManager.h"
@interface TongzhiViewController ()

@property (nonatomic, strong) NSMutableArray *ypList;
@property (nonatomic, strong) UIButton *back;
@property (weak, nonatomic) IBOutlet UILabel *idLbl;
@property (weak, nonatomic) IBOutlet UILabel *titleLbl;
@property (weak, nonatomic) IBOutlet UILabel *sendDateLbl;
@property (weak, nonatomic) IBOutlet UIWebView *contentView;
@property (nonatomic,strong) SXDetailModel *detailModel;
@property (nonatomic, strong) NetworkManager *networkManager;
@property (nonatomic, strong) MBProgressHUD *HUD;

@end

@implementation TongzhiViewController

@synthesize dataList = _dataList;
@synthesize showData = _showData;

- (void)viewDidLoad
{
    [self.navigationController setNavigationBarHidden:YES];
    self.networkManager = [[NetworkManager alloc] init];
    self.detailModel = [[SXDetailModel alloc] init];
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.delegate = self;
    [super viewDidLoad];
}

- (IBAction)backToPre:(id)sender {
   [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    NSDictionary *data = self.wzInfo;
    NSLog(@"data: %@",data);
    NSString *id = [data objectForKeyOrNil:@"id"];
    NSString *title = [data objectForKeyOrNil:@"title"];
    NSString *sendDate = [data objectForKeyOrNil:@"sendDate"];
    NSString *unicodeStr = [title stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.titleLbl.text = unicodeStr;
    self.sendDateLbl.text = sendDate;
    
    [self getContent:id];
}

//根据已有数据刷新界面
- (void)updateViewWithData {
    NSDictionary *data = self.wzInfo;
    NSLog(@"data: %@",data);
    NSString *id = [data objectForKeyOrNil:@"id"];
    NSString *title = [data objectForKeyOrNil:@"title"];
    NSString *sendDate = [data objectForKeyOrNil:@"sendDate"];
    NSString *unicodeStr = [title stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.titleLbl.text = unicodeStr;
    self.sendDateLbl.text = sendDate;
    
    [self getContent:id];
}

-(void) getContent:(NSString*)id {
    UserInfo *user = [UserInfo instance];
    NSString *user_id = [user.info objectForKey:@"id"] ;
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           id,@"tongzhi_id",
                           user_id ,@"user_id",nil];
    [self.networkManager requestWithMethod:tongzhiDetail parameter:param delegate:self];
    [self.HUD show:YES];
}


- (void)refreshViewByReloadData {
    [self getYpList];
}

- (void)getYpList {
    [self.ypList removeAllObjects];
    
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    if (methodId == tongzhiDetail) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            if([result isEqualToString:@"000"]){
                NSArray *results = [data objectForKeyOrNil:@"tongzhi"];
                 if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                    NSString *content = [results valueForKey:@"content"];
                    NSString *unicodeContent = [content stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    self.detailModel.body = unicodeContent;
                    [self showInWebView];
                }
            }
        }
        
    }
    
}


#pragma mark - ******************** 拼接html语言
- (void)showInWebView
{
    NSMutableString *html = [NSMutableString string];
    [html appendString:@"<html>"];
    [html appendString:@"<head>"];
    [html appendFormat:@"<link rel=\"stylesheet\" href=\"%@\">",[[NSBundle mainBundle] URLForResource:@"SXDetails.css" withExtension:nil]];
    [html appendString:@"</head>"];
    
    [html appendString:@"<body>"];
    [html appendString:[self touchBody]];
    [html appendString:@"</body>"];
    
    [html appendString:@"</html>"];
    _contentView.frame  = CGRectMake(15, 135, self.view.frame.size.width-20, self.view.frame.size.height-135);

    [self.contentView setScalesPageToFit:YES];
    [self.contentView loadHTMLString:html baseURL:nil];
    
}

- (NSString *)touchBody
{
    NSMutableString *body = [NSMutableString string];
    if (self.detailModel.body != nil) {
        [body appendString:@"<div class=\"content\">"];
        [body appendString:self.detailModel.body];
        [body appendString:@"</div>"];
    }
    // 遍历img
    for (SXDetailImgModel *detailImgModel in self.detailModel.img) {
        NSMutableString *imgHtml = [NSMutableString string];
        
        // 设置img的div
        [imgHtml appendString:@"<div class=\"img-parent\">"];
        
        // 数组存放被切割的像素
        NSArray *pixel = [detailImgModel.pixel componentsSeparatedByString:@"*"];
        CGFloat width = [[pixel firstObject]floatValue];
        CGFloat height = [[pixel lastObject]floatValue];
        // 判断是否超过最大宽度
        CGFloat maxWidth = [UIScreen mainScreen].bounds.size.width * 0.96;
        if (width > maxWidth) {
            height = maxWidth / width * height;
            width = maxWidth;
        }
        
        NSString *onload = @"this.onclick = function() {"
        "  window.location.href = 'sx:src=' +this.src;"
        "};";
        [imgHtml appendFormat:@"<img onload=\"%@\" width=\"%f\" height=\"%f\" src=\"%@\">",onload,width,height,detailImgModel.src];
        // 结束标记
        [imgHtml appendString:@"</div>"];
        // 替换标记
        [body replaceOccurrencesOfString:detailImgModel.ref withString:imgHtml options:NSCaseInsensitiveSearch range:NSMakeRange(0, body.length)];
    }
    return body;
}


- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    [self.HUD hide:YES];
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"获取失败，请稍后重试";
        }
    }
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_showData count]>0?[_showData count]:0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *TableSampleIdentifier = @"TableSampleIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             TableSampleIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:TableSampleIdentifier];
    }
    if (_showData != nil && _showData.count >0) {
        NSUInteger row = [indexPath row];
        cell.textLabel.text = [_showData objectAtIndex:row];
    }
    return cell;
}
@end